dex<template>
    <div class="h-full w-full">
      <SplitPanel :style="{ 'flex-direction': 'row !important' }" class="dept-page-box">
        <template #left-content>
          <div class="flex justify-between flex-col h-full">
            <a-input-search
              v-model:value="searchValue"
              style="margin-bottom: 8px"
              placeholder="请输入"
            />
            <Tree
              v-model:expandedKeys="state.expandedKeys"
              auto-expand-parent
              :tree-data="state.orgTree"
            >
            <template #title="treeItem">
              <span  
              @click="(val) => onTreeSelect([treeItem.id],treeItem)"
              >
                {{ treeItem.title }}
              </span>
              <NDropDown
                :dropItems="dropItems"
                @click="(val) => handleTreeItemClick(val, treeItem)"
                class="ml-10px"
              />
            </template>
            </Tree>
          </div>
        </template>
        <template #right-content>
          <DynamicTable show-index :data-request="loadTableData" :columns="columns">
            <template #toolbar>
              <a-button type="primary" @click="openModal"> <PlusOutlined /> 新增 </a-button>
            </template>
          </DynamicTable>
        </template>
      </SplitPanel>
    </div>
  </template>
  
  <script setup lang="tsx">
    import { ref, reactive, defineComponent, onMounted, h, watch, unref,nextTick } from 'vue';
    import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons-vue';
    import { Tree, Modal, Alert, message } from 'ant-design-vue';
    import type { FormInstance } from 'ant-design-vue';
    import { 
      baseColumns,
      type PubStationListItem,
      type TableColumnItem } from '@/views/organization/commStation/columns';
    import {formatFormSortTree} from '@/views/organization/orgs/columns';
    import type { LoadDataParams } from '@/components/core/dynamic-table';
    import type { TreeDataItem } from '@/core/permission/utils';
    import { SplitPanel } from '@/components/basic/split-panel';
    import { useTable } from '@/components/core/dynamic-table';
    import { getOrgList } from '@/api/organization/orgs/orgs';
    import { pubStationListPage, getPostTypeEntityList,createPubStation,addPostType,updataPostType,
       updatePubStation, deletePubStation,deletePostType } from '@/api/organization/commStation/index';
    import { flatTree ,formatDept2Tree} from '@/core/permission/utils';
    import { useModal } from '@/hooks/useModal/useModal';
    import Detail from '@/views/organization/commStation/detail.vue';
    import StationType from '@/views/organization/commStation/stationType.vue';
    import { cloneDeep } from 'lodash-es';
    import {handleTree} from '@/utils/common';
    import NDropDown from '@/components/business/tooltip/index.vue';
    import { getDepartmentEntityList } from '@/api/organization/depts/depts';
    import { blankData } from '@/views/organization/commStation/formSchemsa';
  
    defineOptions({
      name: 'sys_commstation',
    });
    defineComponent({
        Detail,StationType
    })
  
    interface State {
      name: string;
      dataModel:string;
      orgId: string[];
      stationTree:[],
      originData: any;
      orgTree: TreeDataItem[];
      showTree:boolean;
    }
  
    const [DynamicTable, dynamicTableInstance] = useTable({ formProps: { autoSubmitOnEnter: true } });
  
    const [ModalRender, modalRef] = useModal();
    const groupDetailRef = ref<FormInstance>();
      const typeDetailRef = ref<FormInstance>();
  
    const editDrawerBindValue = reactive({
      orgData: [],
      users:[],
      stationTree:[],
      stationItem: {},
    });
    const editTyptBindValue = reactive({
      orgTree:[],
      orgItem:{}, 
    });
  
    const searchValue = ref('');
  
    const searchTree = (tree, keyword, includeChildren = false) => {
      const newTree: any = [];
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.title.includes(keyword)) {
          if (!state.orgId.includes(node.key) && node.children && node.children.length) {
            state.orgId.push(node.key);
          }
          newTree.push({
            ...node,
            children: includeChildren ? searchTree(node.children || [], '', true) : [],
          });
        } else if (node.children) {
          const result = searchTree(node.children, keyword, true);
          if (result.length > 0) {
            state.orgId.push(node.key);
            newTree.push({ ...node, children: result });
          }
        }
      }
      return newTree;
    };
  
    watch(
      () => searchValue.value,
      (newVal) => {
        state.orgTree = searchTree(state.originData, newVal, true);
      },
    );
  
    const deptListLoading = ref(false);
  
    const state = reactive<State>({
      name: '',
      dataModel:'',
      orgId: [],
      orgTree: [],
      stationTree:[],
      originData: [],
      showTree:true
    });
    type blankDataType=API.CreatePubStParams;
    const stationBlankData:blankDataType={
      /**
      * id
      */
      id: '',
      /**
      * 群组名称
      */
      name: '',
      /**
      * 群组编码
      */
      code: '',
      /**
       * 上级岗位
       */
       parentId: '',
      /**
      * 所属组织
      */
      orgId: [],
      /**
      * 群组类型
      */
      postType: '',
      /**
      * 群组领导
      */
      leader: '',
      /**
      * 领导名称
      */
      leaderName: '',
      /**
      * 排序号
      */
      postSort: undefined,
      /**
      * 备注
      */
      remark: '',
      /**
      * 是否启用
      */
      IS_ENABLED: 1,
       /**
      * 是否业务相关
      */
      IS_BUSINESS: 0,
    };
    /**
     * @description 打开用户弹窗
     */
     const openModal = async (record: Partial<PubStationListItem> = {}) => {
      console.log(state.stationTree,"11111111111111111")
        editDrawerBindValue.orgData=state.stationTree;
        editDrawerBindValue.stationTree=state.orgTree;
        editDrawerBindValue.users=[];
        editDrawerBindValue.stationItem=record.id?{...record}:{...stationBlankData};
        if(record.id){
        //   const groupUserRes=await getUserByGorupId(record);
        //   editDrawerBindValue.users=groupUserRes.rows;
        }
        ModalRender.show({
            title: `${record.id ? '编辑' : '新增'}公共岗`,
            width: '50%',
            // 是否显示右上角确定取消
            defaultExtra: true,
            destroyOnClose: true,
            content: () => {
            return <Detail  ref={groupDetailRef} defaultData={unref(editDrawerBindValue)}></Detail>;
            },
            // 确定方法执行
            onOk: async (values) => {
                const [groupInfo,groupRef] = await groupDetailRef.value?.handleSubmit();
                let res = await groupRef.value.validate()
                if (res) {
                    const createPostData=cloneDeep(groupInfo);
                    console.log(groupInfo,"groupInfo11111")
                    if(groupInfo.orgId!==undefined&&groupInfo.orgId.length>0&&Array.isArray(groupInfo.orgId)){
                        const orgIdStr=createPostData.orgId.map(item=>item.toString());
                        const orgIds=orgIdStr.join(',');
                        createPostData.orgId=orgIds;
                    }
                    createPostData.id=record.id ? record.id:"";
                    const result=await (record.id ? updatePubStation : createPubStation)(createPostData);
                    if(result.error===200){
                      state.showTree = false
                      const msg=record.id ? "修改成功":"新增成功";
                      message.success(msg);
                      fetchCompanyList();
                      dynamicTableInstance?.reload();
                      nextTick(()=>state.showTree = true)
                    }
                };
            },
      });
    };
    const openTypeModal = async (record: Partial<PubStationListItem> = {}) => {
        editTyptBindValue.orgTree=record.id?[
            {
              title: '分类',
              key: '0',
              value: '0',
              children:null
            }
          ]:state.orgTree;
        editTyptBindValue.orgItem=record.id?{...record}:{...blankData};
        ModalRender.show({
            title: `${record.id ? '编辑' : '新增'}类型`,
            width: '50%',
            // 是否显示右上角确定取消
            defaultExtra: true,
            destroyOnClose: true,
            content: () => {
            return <StationType  ref={typeDetailRef} defaultData={unref(editTyptBindValue)}></StationType>;
            },
            // 确定方法执行
            onOk: async (values) => {
                const [groupInfo,groupRef] = await typeDetailRef.value?.handleSubmit();
                let res = await groupRef.value.validate()
                if (res) {
                    const createPostData=cloneDeep(groupInfo);
                    console.log(groupInfo,"groupInfo11111")
                    // if(groupInfo.orgId!==undefined&&groupInfo.orgId.length>0&&Array.isArray(groupInfo.orgId)){
                    //     const orgIdStr=createPostData.orgId.map(item=>item.toString());
                    //     const orgIds=orgIdStr.join(',');
                    //     createPostData.orgId=orgIds;
                    // }
                    // createPostData.id=record.id ? record.id:"";
                    const result=await (record.id ? updataPostType : addPostType)(groupInfo);
                    if(result.status===200){
                      state.showTree = false
                      const msg=record.id ? "修改成功":"新增成功";
                      message.success(msg);
                      fetchCompanyList();
                      dynamicTableInstance?.reload();
                      nextTick(()=>state.showTree = true)
                    }
                };
            },
      });
    };
  
  
    /**
     * 获取组织列表
     */
    const fetchCompanyList = async () => {
      deptListLoading.value = true;
      const res = await getPostTypeEntityList({id:'',name:''}).finally(() => (deptListLoading.value = false));
      console.log(res);
      if (res && res.result) {
        if(res.result.length>0){
          const dept = flatTree(res.result);
          state.orgTree = formatDept2Tree(dept, '0');
          state.originData = state.orgTree.map((item) => item);
          state.orgId = [
            ...state.orgId,
            ...state.orgTree.map((n: any) => Number(n.id)),
          ];
        }
        else{
          state.orgTree=[
            {
              title: '分类',
              key: '0',
              value: '0',
              children:null
            }
          ]
        }
      }
      const res1 = await getDepartmentEntityList().finally(() => (deptListLoading.value = false));
      //const res = await getOrgList().finally(() => (deptListLoading.value = false));
      if (res1 && res1.result) {
        const orgs = flatTree(res1.result);
        state.stationTree = formatFormSortTree(orgs, '0');
      }
    };
  
    /**
     * @description 表格删除行
     */
    const delRowConfirm = async (userId: number) => {
      const res = await deletePubStation({ id: userId }).finally(dynamicTableInstance?.reload);
      if (res?.error == 200) {
        state.showTree = false;
        message.success('删除成功');
        fetchCompanyList();
        dynamicTableInstance?.reload();
        nextTick(()=>state.showTree = true)
      }
    };
    const dropItems = ref([
    {
            label: '新建分类',
            key: 'addType',
            icon: h(PlusOutlined),
          },
          {
            label: '编辑分类',
            key: 'editType',
            icon: h(EditOutlined),
          },
          {
            label: '删除分类',
            key: 'deleteType',
            icon: h(DeleteOutlined),
          }
    ]);
    /**
     * 点击组织
     */
    const onTreeSelect = (selectedKeys: string[],e) => {
      state.orgId = selectedKeys;
      
      dynamicTableInstance?.reload?.();
    };
  
    const loadTableData = async (params: LoadDataParams) => {
      let  parentId="";
    if(params.name==undefined||params.name==''){
      parentId=state.orgId.length ? state.orgId[0] : '';
    }
      const data = await pubStationListPage({
        ...params,
        pageSize: params.limit,
        postType: parentId,
        name: state.name.length ? state.name : '',
      });
      // const treeData=cloneDeep(data.rows);
      // const tree = handleTree(treeData, "id","parentId");
      // state.stationTree=tree;
      return {
        list: data?.rows || [],
        pagination: {
          total: data?.total,
          size: params.limit,
          page: params.pageNum,
        },
      } as API.TableListResult;
    };
  
    const columns: TableColumnItem[] = [
      ...baseColumns,
      {
        title: '操作',
        width: 220,
        dataIndex: 'ACTION',
        align: 'center',
        actions: ({ record }) => [
          {
            label: '编辑',
            icon: h(EditOutlined),
            onClick: () => openModal(record),
          },
          {
            label: '删除',
            danger: true,
            icon: h(DeleteOutlined),
            popConfirm: {
              title: '你确定要删除吗？',
              onConfirm: () => delRowConfirm(record.id),
            },
          },
        ],
      },
    ];
    const handleTreeItemClick = (node, treeNode) => {
      if(node.key==="addType"){
        openTypeModal({});
      }
      else if(node.key==="editType"){
        openTypeModal(treeNode);
      }
      else if(node.key==="deleteType"){
        deleteTypeInfo();
      }
    };
    const deleteTypeInfo= async()=>{
      Modal.confirm({
      title: '确认删除',
      content: '确定要删除此类型吗？',
      okText: '确定',
      cancelText: '取消',
      centered: true, 
      async onOk() {
        const res = await deletePostType({ id: state.orgId[0] }).finally(dynamicTableInstance?.reload);
        if (res?.error == 200) {
          state.showTree = false;
          message.success('删除成功');
          fetchCompanyList();
          dynamicTableInstance?.reload();
          nextTick(()=>state.showTree = true)
        }
        }
      });
    }
 
    onMounted(() => {
      fetchCompanyList();
    });
  </script>
  
  <style lang="less" scoped>
    @import '@/styles/navTheme.less';
    @classBacks: dept-page-box;
    .customSetStyle(@classBacks, background-color, 'content-back-user');
  
    :deep(.ant-tree) {
      flex: 1;
    }
  </style>
  